package com.asset.dispoal.poi.tools.tool;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CenterCellStyleStrategy extends AbstractColumnWidthStyleStrategy {

    private final Map<String, Map<Integer, Integer>> cache = new HashMap<>();

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheet, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !cellDataList.isEmpty();
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap = cache.computeIfAbsent(writeSheet.getSheetName(), k -> new HashMap<>());
            Integer columnWidth = this.dataLength(cellDataList, isHead);
            if (columnWidth >= 0) {
                if (columnWidth > 255) {
                    columnWidth = 255;
                }
                Integer maxColumnWidth = maxColumnWidthMap.get(head.getColumnIndex());
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(head.getColumnIndex(), columnWidth);
                    writeSheet.getSheet().setColumnWidth(head.getColumnIndex(), columnWidth * 768);
//                    CellStyle cellStyle = writeSheet.getSheet().getColumnStyle(head.getColumnIndex());
//                    cellStyle.setAlignment(HorizontalAlignment.CENTER);
//                    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//                    writeSheet.getSheet().setDefaultColumnStyle(head.getColumnIndex(), cellStyle);
                }
            }
        }
    }


    // 计算单元格内容的长度（这里简单处理为字符串长度，可以根据需要调整）
    private int dataLength(List<WriteCellData<?>> cellDataList, boolean isHead) {
        try {
            WriteCellData cellData = cellDataList.stream().max(Comparator.comparingInt(writer -> writer.getStringValue().length())).get();
            return cellData.getStringValue().length();
        } catch (Exception e) {
            return 20;
        }

    }

}